package cc.autoapi.pucong.auto.flow.core.root.utils;

import cc.autoapi.pucong.auto.flow.core.root.selfenum.CommonEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

/**
 * 视图配置、返回enum json配置
 *
 * @author pucong
 * @date 2017-05-23
 */
public class EnumConvertFactory implements ConverterFactory<Integer, CommonEnum> {

    @Override
    public <T extends CommonEnum> Converter<Integer, T> getConverter(Class<T> targetType) {
        return new IntegerToIEum(targetType);
    }

    /**
     * string 值转枚举类
     *
     * @param <T>
     */
    private static class IntegerToIEum<T extends CommonEnum> implements Converter<Integer, T> {
        private Class<T> targerType;

        /**
         * Instantiates a new String to i eum.
         *
         * @param targerType the targer type
         */
        public IntegerToIEum(Class<T> targerType) {
            this.targerType = targerType;
        }

        @Override
        public T convert(Integer source) {
            if (source == null) {
                return null;
            }
            return (T) getIEnum(this.targerType, source);
        }

        /**
         * Gets i enumSelf.
         * 1.对比是否和值相同
         * 2.对比是否和code相同
         *
         * @param <T>        the type parameter
         * @param targerType the targer type
         * @param source     the source
         * @return the i enumSelf
         */
        private <T extends CommonEnum> Object getIEnum(final Class<T> targerType, Integer source) {
            for (T enumObj : targerType.getEnumConstants()) {
                if (source.equals(enumObj.getValue())) {
                    return enumObj;
                }
            }
            return null;
        }
    }


}
